package leetcode_day._2022._202201._0110;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/1/5 13:46
 * 替换所有的问号
 * 算法：模拟
 * 只要与左右两边的字符不一样，所以只需三次就能找到
 */
public class _05_1576 {
    public static void main(String[] args) {
        System.out.println(new _05_1576().modifyString_perfect("??yw?ipkj?"));
    }

    public String modifyString(String s) {
        int n = s.length();
        if (n == 1) return "a";
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '?') {
                if (i == 0) ans.append(s.charAt(i + 1) == '?' ? 'z' : getNewChar(s.charAt(i + 1)));
                else if (i == n - 1) ans.append(getNewChar(ans.charAt(ans.length() - 1)));
                else {
                    char newC = getNewChar(ans.charAt(ans.length() - 1));
                    while (newC == s.charAt(i + 1)) newC = getNewChar(newC);
                    ans.append(newC);
                }
            } else ans.append(s.charAt(i));
        }
        return ans.toString();
    }

    char getNewChar(char c) {
        char newC = (char) (c - 1);
        if (newC < 'a') newC = 'z';
        return newC;
    }

    public String modifyString_perfect(String s) {
        final char[] cs = s.toCharArray();
        int n = cs.length;
        for (int i = 0; i < n; i++) {
            for (int c = 0; c < 3 && cs[i] == '?'; c++) {
                boolean ok = true;
                if (i - 1 >= 0 && cs[i - 1] == c + 'a') ok = false;
                if (i + 1 < n && cs[i + 1] == c + 'a') ok = false;
                if (ok) cs[i] = (char) (c + 'a');
            }
        }
        return String.valueOf(cs);
    }

}
